<?php
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
jimport('joomla.application.component.helper');
jimport('joomla.filesystem.file');
              
class DocarioModelFile extends JModel {
    var $_file;
    var $_category;
    var $_data;
    var $_id;
    var $_catid;
    
    var $_pagination;
    var $_total;
    
    var $_query;

    function __construct() {
        parent::__construct();
        
        $mainframe = JFactory::getApplication();
        
        $limit = $mainframe->getUserStateFromRequest('global.list.limit','limit',$mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
    }
    
    function setId($id) { $this->_id = $id; $this->_file = null; }
    function setCatId($cid) {
        $this->_catid = $cid;
    }
    
    function getPagination() {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(),
                                                 $this->getState('limitstart'),
                                                 $this->getState('limit'));
        }
        return $this->_pagination;
    }
    
    function getTotal() {
        $this->_buildQuery();
        if (empty($this->_total)) {
            $this->_total = $this->_getListCount($this->_query);
        }
        return $this->_total;
    }
    
    function _buildQuery() {
        $this->_query = 'select * from #__docario_file';
        return $this->_query;
    }
    
    function _buildFilter() {
        $this->_query .= ' where 1=1';
        if (isset($this->_catid)) {
            $this->_query .= ' and catid='.$this->_catid;
        }
    }
    
    function getData() {
        $this->_buildQuery();
        $this->_buildFilter();
        if (empty($this->_data))
            $this->_data = $this->_getList($this->_query, 
                                           $this->getState('limitstart'),
                                           $this->getState('limit'));
        $this->_db->getQuery();
        return $this->_data;
    }
    
    function getCategories() {
        $query = 'select * from #__docario_category';
        $query .= ' where parent_id='.$this->_catid;
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function getAllCategories() {
        $query = 'select * from #__docario_category';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function _loadCategory() {
        if (empty($this->_category)) {
            $query = 'select * from #__docario_category where id='.$this->_catid;
            $this->_db->setQuery($query);
            $this->_category = $this->_db->loadObject();
        }
    }
    
    function _initCategory() {
        if (empty($this->_category)) {
            $category = new stdClass();
            $category->id = 0;
            $category->name = '';
            $category->alias = '';
            $category->description = '';
            $category->published = '';
            $this->_category = $category;
            return (boolean) $this->_category;
        }
        return true;
    }
    
    function getCategory() {
        if ($this->_loadCategory()) {
        } else $this->_initCategory();
        return $this->_category;
    }
    
    function _loadFile() {
        if (empty($this->_file)) {
            $query = 'select * from #__docario_file a';
            $query .= ' left join #__docario_file_revision b';
            $query .= ' on b.file_id=a.id where a.id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_file = $this->_db->loadObject();
        }
    }
    
    function _initFile() {
        if (empty($this->_file)) {
            $file = new stdClass();
            $file->id = 0;
            $file->catid = 0;
            $file->userid = 0;
            $file->name = '';
            $file->alias = '';
            $file->description = '';
            $file->download_filename = '';
            
            $this->_file = $file;
            return (boolean) $this->_file;
        }
        return true;
    }
    
    function getFileTmp($file_name) {
        $query = 'select * from #__docario_file_tmp';
        $query .= ' where file_name="'.$file_name.'"';
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
    
    function removeFileTmp($file) {
        $query = 'delete from #__docario_file_tmp';
        $query .= ' where id='.$file->id;
        $this->_db->setQuery($query);
        $this->_db->query();
    }
    
    function cleanTmp() {
        $query = 'delete from #__docario_file_tmp';
        $this->_db->setQuery($query);
        $this->_db->query();
    }
    
    function getFile() {
        if ($this->_loadFile()) {
        } else $this->_initFile();
        return $this->_file;
    }
    
    function getFileByName($name) {
        $query = 'select * from #__docario_file';
        $query .= ' where download_filename="'.$name.'"';
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
    
    function _generateFileName($file, &$exists, &$file_name) {
        $options = JComponentHelper::getParams('com_docario');
        $storebase = $options->get('storebase');
        $storepath = $options->get('storepath');
        
        if ($storebase) {
            $basepath = JPATH_SITE . DS . $storepath;
        } else $basepath = $storepath;
        
        if (!JFolder::exists($basepath)) {
            mkdir($basepath, 0755, true);
        }
        
        $origname = JRequest::getVar('catid') . '.' . $file['name'];
        $filename = $origname;
        $i = 0;
        while (JFile::exists($basepath . DS . $filename)) { 
            $exists = true;
            $i++;
            $filename = $i . '.' . $origname;
        }
        $file_name = $filename;
        return $basepath . DS . $filename;
    }
    
    function newFile(&$file, &$file_name) {
        $file['name'] = JFile::makeSafe($file['name']);
        $exists = false;
        $destname = $this->_generateFileName($file, $exists, $file_name);
        
        JFile::upload($file['tmp_name'], $destname);
        
        $query = 'insert into #__docario_file_tmp (name, file_name, ';
        $query .= 'mime_type, size) values ("'.$file['name'].'", ';
        $query .= '"'.$file_name.'", "'.$file['type'].'", '.$file['size'].')';
        $this->_db->setQuery($query);
        $this->_db->query();
        
        return $exists;
    }
    
    function save() {
        $id = JRequest::getVar('id');
        $file_tmp_id = JRequest::getVar('file_tmp_id');
        
        $catid = JRequest::getVar('file_catid');
        $user = JFactory::getUser();
        $userid = $user->id;
        $name = JRequest::getVar('file_name');
        $alias = JRequest::getVar('file_alias');
        $description = JRequest::getVar('file_description');
        $download_filename = JRequest::getVar('download_filename');
        $mime_type = JRequest::getVar('mime_type');
        
        if ($id == 0) {
            $query = 'insert into #__docario_file (catid, userid, name, alias, ';
            $query .= ' description, download_filename, mime_type) values (';
            $query .= $catid.', '.$userid.', "'.$name.'", "'.$alias.'", ';
            $query .= '"'.$description.'", "'.$download_filename.'", ';
            $query .= '"'.$mime_type.'")';
        } else {
            $query = 'update #__docario_file set catid='.$catid.', ';
            $query .= ' name="'.$name.'", alias="'.$alias.'", ';
            $query .= ' description="'.$description.'", ';
            $query .= ' download_filename="'.$download_filename.'", ';
            $query .= ' mime_type="'.$mime_type.'" where id='.$id;
        }
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        if ($file_tmp_id > 0) {
            if ($id == 0) { $id = $this->_db->insertid(); }
            
            $query = 'select * from #__docario_file_tmp where id='.$file_tmp_id;
            $this->_db->setQuery($query);
            $file_tmp = $this->_db->loadObject();
            
            $query = 'update #__docario_file_revision set default_rev=0';
            $query .= ' where file_id='.$id;
            
            $this->_db->setQuery($query);
            $this->_db->query();
            
            $query = 'insert into #__docario_file_revision (file_id, ';
            $query .= 'local_filename, file_size, default_rev) value ('.$id.', ';
            $query .= '"'.$file_tmp->file_name.'", '.$file_tmp->size.', 1)';
            
            $this->_db->setQuery($query);
            $this->_db->query();
            
            $query = 'delete from #__docario_file_tmp where id='.$file_tmp_id;
            $this->_db->setQuery($query);
            $this->_db->query();
        }
    }
    
    function getFileUserPermissions($search = '') {
        $query = 'select * from #__users a';
        $query .= ' left join (select * from #__docario_file_user_allowed';
        $query .= ' where file_id='.$this->_id.' or file_id is null) b';
        $query .= ' on b.userid=a.id where a.name like "%'.$search.'%"';
        $query .= ' or a.username like "%'.$search.'%"';
        
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function getUsers($search = '') {
        $query = 'select * from #__users';
        $query .= ' where name like "%'.$search.'%"';
        $query .= ' or username like "%'.$search.'%"';
        
        $this->_db->setQuery($query);
        echo $this->_db->getQuery();
        return $this->_db->loadObjectList();
    }
}
?>
